<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/8/17
 * Time: 14:53
 */

error_reporting(0);
use think\facade\Db;
use think\facade\Cache;

//use think\response\Json;
header('Content-Type: text/html;charset=utf-8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:*');
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");
header('Access-Control-Allow-Credentials:true');//表示是否允许发送Cookie





define('API_HOST',$_SERVER['HTTP_HOST']);//获取当前域名
define('SHUJUCUNCHU',app()->getRootPath().'public');
if(!is_dir(SHUJUCUNCHU)){
    mkdir(SHUJUCUNCHU,0777,true);
}



//订单编号
function ordersn(){
    $osn = "9633".date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    return $osn;
}
//支付编号
function payordersn($uid){
    $payorder = mt_rand(10,99) . sprintf('%010d',time() - 946656000) . sprintf('%03d', (float) microtime() * 1000) . sprintf('%03d', (int) $uid % 1000);
    return $payorder;
}

function write_txt($dir,$data=""){
    $years = date('Y-m');
    //设置路径目录信息
    $url = './log/'.$years.'/'.date('Ymd').'txt';
//    $dir_name=dirname($url);
    dd222($dir.$url);die;
    //目录不存在就创建
    if(!file_exists($dir_name))
    {
        //iconv防止中文名乱码
        $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
    }
    $fp = fopen($url,"a");//打开文件资源通道 不存在则自动创建
    fwrite($fp,date("Y-m-d H:i:s").var_export($data,true)."\r\n");//写入文件
    fclose($fp);//关闭资源通道
}

/**
 *日志记录，按照"Ymd.log"生成当天日志文件
 * 日志路径为：入口文件所在目录/logs/$type/当天日期.log.php，例如 /logs/error/20120105.log.php
 * @param string $type 日志类型，对应logs目录下的子文件夹名
 * @param string $content 日志内容
 * @return bool true/false 写入成功则返回true
 */
function write_log($type,$content=""){
    if(!$type || !$content  ){
        return FALSE;
    }
    $yearlog = date("Y年m月");
    $dir=getcwd().DIRECTORY_SEPARATOR.'logs'.DIRECTORY_SEPARATOR.$type.DIRECTORY_SEPARATOR.$yearlog;
    if(!is_dir($dir)){
        if(!mkdir($dir,0777,true)){
            return false;
        }
    }
    $filename=$dir.DIRECTORY_SEPARATOR.date("Ymd",time()).'.log';
//    $logs= array("time"=>date("Y-m-d H:i:s"),"content"=>$content);
    $str="\r\n".var_export($content, true);
    if(!$fp=@fopen($filename,"a")){
        return false;
    }
    if(!fwrite($fp, $str))return false;
    fclose($fp);
    return true;
}



function Debug($msg='测试用', $data = null) {
    $data=['name'=>'zhangsan','age'=>14];
    \SeasLog::setBasePath(App::getRuntimePath());
    $strOut = '';
    if ($data != null) {
        if (is_array($data) || is_object($data)) $strOut .= "\n" . print_r($data, true);
        else  $strOut .= "\n$data\n";
    } else $strOut = "\n";
    $msg = "[default] $msg" . $strOut;

    \SeasLog::info($msg, array(['sax'=>1212]), 'q_contract');
}

/**
 * post/https请求
 * @param $url
 * @param $post
 * @return bool|string
 */
if (!function_exists('post_curls')) {
    function post_curls($url, $post)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $output = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $output; // 返回数据，json格式
    }
}

//日期函数
function date_ymd(){
    return date('Y-m-d H:i:s',time());
}

function sp_log($content,$file="log.txt"){
    file_put_contents($file, $content,FILE_APPEND);
}

//  获取13位时间戳
function getMillisecond(){
    list($t1, $t2) = explode(' ', microtime());
    return sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
}






/**
 * 随机字符串生成
 * @param int $len 生成的字符串长度
 * @return string
 */
function sp_random_string($len = 6) {
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );
    $charsLen = count($chars) - 1;
    shuffle($chars);    // 将数组打乱
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}


//获取日期
function getday(){
    $date = [
        'threeday' => date("Y-m-d",strtotime("+3 day")),//3天后
        'sevenday' => date("Y-m-d",strtotime("+7 day")),//7天后
        'week' => date("Y-m-d",strtotime("+1 week")),//一周天后
        'month' => date("Y-m-d",strtotime("+1 month")),//一月后
        'month3' => date("Y-m-d",strtotime("+3 month")),//一季度后
        'month6' => date("Y-m-d",strtotime("+6 month")),//半年后
        'year' => date("Y-m-d",strtotime("+1 year")),//一年后
    ];
    return $date;
}


function strarray($str){
    $arr = explode(',',$str);
    return $arr;
}

//日志函数  $logtype 表示 1 正常操作日志 2 代表充值记录
function user_log($username,$uid,$content,$logtype=1){
    $data = [
        'username'=>$username,
        'logip' => get_client_ip(),
        'logtime'=> time(),
        'uid'=> $uid,
        'logtype'=> $logtype,
        'content' => $content
    ];
    Db::name('user_log') -> insert($data);
}
